import React, { Component } from 'react'
import { connect } from 'react-redux'
import { messages, queryCurrencyPrecision } from "share/common";
import NumberRange from "containers/financial-management/expense-view/component/number-range";
import Partner from "containers/pay/template/partner"
import CostCenterSearchForm from "components/template/cost-center-search-form/cost-center-search-form";
import moment from "moment";
import { Badge, Dropdown, Icon, Menu, message, Tooltip, Select, Popover } from "antd";
import paymentService from "containers/pay/pay-workbench/pay-workbench.service";
import openSlideFrame from "share/openSlideFrame";
import selectorData from "share/selectorData";
import Selector from "components/selector";
import { orderTab, optionsMap, handleOptions } from "./utils"
import Department from "components/template/department";
import EditSelect from "./edit-select";
import EditCell from "./edit-cell";
import ReceiptUpload from "../pay-workbench/success/receipt-upload"
import EditInput from "./edit-input"

const { Option } = Select;

const DataHoc = WrappedComponent => {
  class hoc extends Component{

    setWrappedInstance = ref => {
      this.wrappedInstance = ref;
    };

    setOfBookId = {
      component: isTitle => <Selector
        allowClear={false}
        type={'setOfBooksByTenant'}
        params={{ roleType: 'TENANT' }}
        entity
        onChange={value => this.handleChangeSetOfBook(value, isTitle)}
      />,
      id: 'setOfBookId',
      judgeInTitle: true,
      label: messages('finance-4.key66')/*账套*/,
      initialValue: {
        setOfBooksName: this.props.company.setOfBooksName,
        id: this.props.company.setOfBooksId
      },
      tagUnclosed: true,
      parser: value => ({ setOfBookId : value ? value.id : undefined }),
      tagParser: value => value.setOfBooksName
    };

    paymentCompanyId = {
      id: 'paymentCompanyId', label: messages('finance-4.key272')/*单据公司*/, component: 'Chooser',
      props: {
        type: 'available_company_setOfBooks',
        labelKey: 'name',
        valueKey: 'id',
        single: true,
        listExtraParams: { enabled: true, setOfBooksId: this.props.company.setOfBooksId }
      },
      initialValue: [{ name: this.props.company.name, id: this.props.company.id }],
      parser: value => ({
        paymentCompanyId: (value && value.length) ? value.map(item => item.id) : null
      })
    };

    documentNumberForm = {
      id: 'documentNumber', label: messages('finance-4.key59')/*单据编号*/, component: 'Selector',
      props: {
        placeholder: messages('common.please.input')/*请输入*/,
        selectorItem: {
          url: `/payment/api/cash/transactionData/documentNumber/keyword`,
          label: '_self', key: '_self', searchKey: 'documentNumber'
        },
        searchIfKeywordIsNull: true
      }
    };

    documentCategory = {
      id: 'documentCategory', label: messages('finance-4.key60')/*单据类型*/, component: isTitle => (
        <Selector
          entity
          type={'value_list'}
          params={{ type: 2106 }}
          itemMap
          onChange={value => this.handleChangeCategory(value, isTitle)}
        />
      ),
      judgeInTitle: true,
      parser: value => ({ documentCategory : value ? value.code : undefined }),
      tagParser: value => {
        return value.messageKey
      }
    };

    formOids = {
      id: 'formOids', label: messages('finance-4.key273')/*表单类型*/, component: 'MultiSelectorV2',
      props: {
        type: 'authority_form',
        labelKey: 'formName',
        isShowSelectAll: true
      },
      parser: value => ({ formOids: value ? value.map(item => item.formOID) : undefined })
    };

    employeeId = {
      id: 'employeeId', label: messages('common.applicant')/*申请人*/, component: 'Selector',
      props: {
        placeholder: messages('common.please.input')/*请输入*/ + messages('finance-4.key235')/*申请人姓名/工号*/,
        selectorItem: {
          ...selectorData['user'],
          key: 'id',
          label: record => (`${record.employeeID}-${record.fullName}${(record.status !== 1001 ?
              (`（${record.status === 1002 ?
                  messages('finance-4.key74')/*待离职员工*/ :
                  messages('finance-4.key75')/*离职员工*/}）`
              ) :
              ''
          )}`)
        },
        searchIfKeywordIsNull: true
      }
    };

    amountRange = {
      id: 'amountRange',
      label: messages('finance-4.key26')/*金额范围*/,
      component: <NumberRange/>,
      parser: value => ({
        amountFrom: value && value[0] ? value[0] : null,
        amountTo: value && value[1] ? value[1] : null
      }),
      tagParser: value => value && (value[0] || value[1]) && `${value[0] === 0 ? value[0] : value[0] || ''} ~ ${value[1] === 0 ? value[1] : value[1] || ''}`
    };

    departmentOids = {
      id: 'departmentOids', label: messages('common.department')/*部门*/, component: <Department/>,
      parser: value => ({ departmentOids: value ? value.map(item => item.departmentOID) : undefined }),
      tagParser: value => (value.map(item => item.title).join(','))
    };

    currencyCode = {
      id: 'currencyCode', label: messages('common.currency')/*币种*/, component: 'Selector',
      props: {
        type: 'currency',
        params: { userOId: this.props.loginUser.userOID },
        filter: item => item.enable,
        showSearch: true
      }
    };

    cshTransactionClassId = {
      id: 'cshTransactionClassId', label: messages('finance-4.key274')/*付款/借款类型*/, component: 'AllSelector',
      props: {
        selectorItem: {
          url: `/api/cash/transaction/classes/queryBytenantId/${this.props.tenant.id}`,
          key: 'id',
          label: 'description'
        },
        params: { setOfBooksId: this.props.company.setOfBooksId }
      },
      parser: value => ({
        cshTransactionClassId: value ? value.map(item => item.id) : null
      })
    };

    costCenterItemOids = {
      id: 'costCenterItemOids', label: messages('finance-4.key146')/*成本中心*/,
      component: <CostCenterSearchForm title={messages('finance-4.key146')/*成本中心*/} type={'id'}/>,
      parser: value => ({
        costCenterParam: value ? JSON.stringify(value) : null
      }),
      tagParser: value => messages('common.total.selected',{arg1: value.length})/*已选 {arg1} 条*/
    };

    handleChangeSetOfBook = (value, isTitle) => {
      const { searchForm } = this.wrappedInstance.state;
      let setOfBooksId = searchForm.find(item => item.id === 'paymentCompanyId').props.listExtraParams.setOfBooksId;
      if (setOfBooksId !== value.id) {
        if (!isTitle) {
          this.wrappedInstance.advancedTableRef.advancedSearchRef.props.form.setFieldsValue({
            paymentCompanyId: undefined,
            cshTransactionClassId: undefined
          });
        }
        searchForm.map(item => {
          if (item.id === 'paymentCompanyId' || item.id === 'cshTransactionClassId') {
            item.props.listExtraParams = { setOfBooksId: value.id, enabled: true };
          }
        });
        this.wrappedInstance.setState({ searchForm });
      }
    };

    handleChangeCategory = (value, isTitle) => {
      const { searchForm } = this.wrappedInstance.state;
      let formType = (searchForm.find(item => item.id === 'formOids').props.params || {}).formType;
      let map = {
        'EXP_REPORT': 1002,
        'PAYMENT_REQUISITION': 3001,
        'ACP_REQUISITION': 7001,
        'VENDOR_PAYMENT': 3004
      };
      if (!value || map[value.code] !== formType) {
        if (!isTitle) {
          this.wrappedInstance.advancedTableRef.advancedSearchRef.props.form.setFieldsValue({
            formOids: undefined,
          });
        }
        searchForm.map(item => {
          if (item.id === 'formOids') {
            item.props.params = { formType: !value ? '' : map[value.code] };
          }
        });
        this.wrappedInstance.setState({ searchForm });
      }
    };

    billCodeForm = { id: 'billcode', label: messages('finance-4.key144')/*付款流水号*/, component: 'Input' };

    customerBatchNoForm = { id: 'customerBatchNo', label: messages('finance-4.key143')/*付款批次号*/, component: 'Input' };

    ledgerStatusForm = {
      id: 'ledgerStatusForm', label: messages('finance-4.key275')/*核算状态*/, component: 'Select',
      children: [<Option key={'F'}>{messages('finance-4.key14')/*生成失败*/}</Option>, <Option key={'S'}>{messages('finance-4.key276')/*生成成功*/}</Option>],
      props: {
        style: { width: '100%' },
        allowClear: true,
        placeholder: messages('common.select')/*请选择*/
      },
      tagParser: value => value === 'F' ? messages('finance-4.key14')/*生成失败*/ : messages('finance-4.key276')/*生成成功*/
    };

    getSearchForm = key => {
      let searchForm = [
        this.setOfBookId,
        this.paymentCompanyId,
        this.documentNumberForm,
        this.documentCategory,
        this.formOids,
        this.employeeId,
        this.amountRange, {
          ...Partner,
          parser: value => value && value.partnerCategory ? {
            partnerCategory: value.partnerCategory.code,
            partnerId: value.partnerId && value.partnerId.length ? value.partnerId[0].id : null
          } : null,
        },
        this.departmentOids,
        this.currencyCode,
        this.cshTransactionClassId,
        this.costCenterItemOids
      ];
      switch (key) {
        case 'Unpaid':
          searchForm = searchForm.concat([{
            id: 'dateRange', label: messages('finance-4.key277')/*申请日期*/, component: 'DateRangePicker',
            parser: value => ({
              requisitionDateFrom: value && value[0] ? moment(value[0]).format('YYYY-MM-DD') : null,
              requisitionDateTo: value && value[1] ? moment(value[1]).format('YYYY-MM-DD') : null
            })
          },{
            id: 'auditDate', label: messages('finance-4.key278')/*审核日期*/, component: 'DateRangePicker',
            parser: value => ({
              auditDateFrom: value && value[0] ? moment(value[0]).format('YYYY-MM-DD') : null,
              auditDateTo: value && value[1] ? moment(value[1]).format('YYYY-MM-DD') : null
            })
          },{
            id: 'auditorId',
            label: messages('finance-4.key279')/*审核人*/,
            component: 'Chooser',
            props: {
              type: 'finance-auditable-users',
              labelKey: 'fullName',
              valueKey: 'id',
              single: true
            },
            parser: value => ({
              auditorId: value && value.length ? value[0].id : null
            }),
            JSONObjectFormatterParams: ['fullName', 'userOID']
          },{
            id: 'pending', label: messages('finance-4.key280')/*暂挂状态*/, component: <Select style={{ width: '100%' }} placeholder={messages('finance-4.key136')/*请选择*/}>
              <Option value={'01'}>{messages('finance-4.key103')/*非暂挂*/}</Option>
              <Option value={'02'}>{messages('finance-4.key104')/*暂挂*/}</Option>
            </Select>,
            tagParser: value => value ? (value === '02' ? messages('finance-4.key104')/*暂挂*/ : messages('finance-4.key103')/*非暂挂*/) : null
          }, {
            id: 'planPayDate', label: messages('finance-4.key288')/*计划付款日期*/, component: 'DateRangePicker',
            parser: value => ({
              planPayDateFrom: value && value[0] ? moment(value[0]).format('YYYY-MM-DD') : null,
              planPayDateTo: value && value[1] ? moment(value[1]).format('YYYY-MM-DD') : null
            })
          }]);
          break;
        case 'Success':
          searchForm = searchForm.concat([this.billCodeForm, this.customerBatchNoForm, {
            id: 'dateRange', label: messages('finance-4.key281')/*支付日期*/, component: 'DateRangePicker',
            parser: value => ({
              payDateFrom: value && value[0] ? moment(value[0]).format('YYYY-MM-DD') : null,
              payDateTo: value && value[1] ? moment(value[1]).format('YYYY-MM-DD') : null
            })
          }, this.ledgerStatusForm]);
          break;
        case 'Paying':
        case 'Fail':
          searchForm = searchForm.concat([this.billCodeForm, this.customerBatchNoForm, {
            id: 'createDate', label: messages('finance-4.key282')/*创建时间*/, component: 'DateRangePicker',
            parser: value => ({
              createDateFrom: value && value[0] ? moment(value[0]).format('YYYY-MM-DD') : null,
              createDateTo: value && value[1] ? moment(value[1]).format('YYYY-MM-DD') : null
            })
          }]);
          break;
        case 'refund-check':
          searchForm = [
            this.setOfBookId, this.paymentCompanyId, this.customerBatchNoForm, this.billCodeForm, this.amountRange,
            {
              id: 'createDate', label: messages('finance-4.key282')/*创建时间*/, component: 'DateRangePicker',
              parser: value => ({
                createDateFrom: value && value[0] ? moment(value[0]).format('YYYY-MM-DD') : null,
                createDateTo: value && value[1] ? moment(value[1]).format('YYYY-MM-DD') : null
              })
            }, {
              ...Partner,
              parser: value => value && value.partnerCategory ? {
                partnerCategory: value.partnerCategory.code,
                partnerId: value.partnerId && value.partnerId.length ? value.partnerId[0].id : null
              } : null,
            }
          ];
          break;
        default:
          break;
      }
      return searchForm;
    };

    companyName = {
      title: messages('finance-4.key272')/*单据公司*/, dataIndex: 'companyName', hide: true
    };

    documentCompanyName = {
      title: messages('finance-4.key272')/*单据公司*/, dataIndex: 'documentCompanyName', hide: true
    };

    departmentName = {
      title: messages('finance-4.key283')/*单据部门*/, dataIndex: 'departmentName', hide: true
    };

    requisitionDate = {
      title: messages('finance-4.key277')/*申请日期*/, dataIndex: 'requisitionDate', width: 105, sorter: true,
      render: value => moment(value).format('YYYY-MM-DD')
    };

    requisitionTime = {
      title: messages('finance-4.key284')/*申请时间*/, dataIndex: 'requisitionTime', width: 105, hide: true,
      render: value => value ? value : '-'
    };

    documentNumber = {
      title: `${messages('finance-4.key59')/*单据编号*/} | ${messages('finance-4.key60')/*单据类型*/}`, width: 165, sorter: true,
      dataIndex: 'documentNumber', render: (value, record) => (<div>
        <a onClick={() => this.handleClickDoc(record)}>{value}</a>
        <span className="ant-divider" />
        {record.documentTypeName}
      </div>)
    };

    employeeName = {
      title: `${messages('common.user.id')/*工号*/} | ${messages('common.applicant')/*申请人*/}`, width: 115,
      dataIndex: 'employeeName', render: (value, record) => (<div>
        {record.employeeCode}
        <span className="ant-divider" />
        {value}
      </div>)
    };

    currency = { title: messages('common.currency')/*币种*/, dataIndex: 'currency', width: 56 };

    unPaidAmount = {
      title: messages('common.total.amount')/*总金额*/, dataIndex: 'amount', width: 72,
      render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currency))
    };

    amount = {
      title: messages('finance-4.key64')/*本次支付金额*/, dataIndex: 'amount', width: 110, sorter: true,
      render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currency))
    };

    unPaidPayableAmount = {
      title: messages('finance-4.key285')/*可支付金额*/, dataIndex: 'payableAmount', render: (value, record) => {
        let numberString = this.filterMoney(value || 0, queryCurrencyPrecision(record.currency), true);
        return (
          value === record.amount ? this.filterMoney(value, queryCurrencyPrecision(record.currency)) :
            <div style={{ textAlign: 'right' }}>
              <Tooltip title={messages('finance-4.key286')/*可支付金额不等于总金额*/}>
                <Icon type="exclamation-circle-o" style={{ color: 'red', marginRight: 5 }} />
              </Tooltip>
              {numberString}
            </div>
        )
      }, width: 98
    };

    unPaidCurrentPayAmount = {
      title: messages('finance-4.key64')/*本次支付金额*/, dataIndex: 'currentPayAmounts', width: 150, sorter: true,
      render: (value, record) => (
        <EditCell
          value={this.filterMoney(record.currentPayAmount, queryCurrencyPrecision(record.currencyCode), true)}
          disable={this.wrappedInstance.state.payAll}
          precision={queryCurrencyPrecision(record.currencyCode)}
          onChange={editValue => this.wrappedInstance.editCurrentPay(editValue, record)}
          style={{textAlign: 'right'}}
        />
      )
    };

    unPaidPaymentMethodCategoryName = {
      title: messages('finance-4.key175')/*付款方式类型*/, dataIndex: 'paymentMethodCategoryNames', width: 170,
      render: (account, record) => (
        <EditSelect
          option={this.wrappedInstance.state.radioOption.map(item => ({ key: item.itemCode, label: item.showName }))}
          value={{
            key: record.paymentMethodCategory,
            label: record.paymentMethodCategoryName
          }}
          onChange={value => this.wrappedInstance.editAccount("paymentMethodCategory", value, record)}
          onChangeError={this.wrappedInstance.state.editCellError}
          disabled={this.wrappedInstance.state.editing || record.accountType === 'ALIPAY_LOGON_ID'}
        />
      )
    };

    paymentMethodCategoryType = {
      title: messages('finance-4.key81')/*付款方式*/, dataIndex: 'paymentMethodName', hide: true
    };

    partnerCategoryName = {
      title: messages('finance-4.key61')/*类型 | 收款方*/, dataIndex: 'partnerCategoryName', width: 115,
      render: (value, record) => (
        <div>
          {value}
          <span className="ant-divider" />
          {record.partnerName}
        </div>
      )
    };

    unPaidAccountNumber = {
      title: messages('finance-4.key62')/*收款账号*/, dataIndex: 'accountNumber', render: (account, record) => (
        <EditSelect
          url={`/api/CompanyBank/selectBankInfo?partnerId=${record.partnerId}&partnerCategory=${record.partnerCategory}&paymentMethodCode=${record.paymentMethodCategory}`}
          valueKey='accountNumber'
          label='viewName'
          blurChange
          value={{
            key: account,
            label: account
          }}
          popOver={() => <div>
            <div>{record.accountName || '-'}</div>
            <div>{record.accountNumber || '-'}</div>
            <div>{record.bankName || '-'}</div>
            <div>{record.bankBranchName || '-'}</div>
          </div>}
          onChange={(value, selectItem) => this.wrappedInstance.editAccount('accountNumber', value, record, selectItem)}
          onChangeError={this.wrappedInstance.state.editCellError}
          disabled={this.wrappedInstance.state.editing}
        />
      ), width: 210
    };

    paymentStatusName = {
      title: messages('common.column.status')/*状态*/, dataIndex: 'paymentStatusName', width: 90,
      render: value => <Badge status='default' text={value} />
    };

    billCode = {
      title: messages('finance-4.key144')/*付款流水号*/, dataIndex: 'billcode', width: 95,
      render: (value, record) => <a onClick={() => this.checkPaymentDetail(record)}>{value}</a>
    };

    customerBatchNo = { title: messages('finance-4.key143')/*付款批次号*/, dataIndex: 'customerBatchNo', width: 95 };

    paymentTypeName = { title: messages('finance-4.key81')/*付款方式*/, dataIndex: 'paymentTypeName' };

    payeeAccountNumber = {
      title: messages('finance-4.key25')/*收款方账号*/, dataIndex: 'payeeAccountNumber', width: 100,
      render: (value, record) => <Popover content={(
        <div>
          <div>{record.payeeAccountName || '-'}</div>
          <div>{record.payeeAccountNumber || '-'}</div>
          <div>{record.payeeBankName || '-'}</div>
          <div>{record.payeeBankBranchName || '-'}</div>
        </div>
      )}>{value}</Popover>
    };

    payDate = {
      title: messages('finance-4.key281')/*支付日期*/, dataIndex: 'payDate', width: 105,
      render: value => value ? moment(value).format('YYYY-MM-DD') : '-'
    };

    cshTransactionClassName = {
      title: messages('finance-4.key287')/*现金事务分类名称字段*/, dataIndex: 'cshTransactionClassName', hide: true,
      render: value => value || '-'
    };

    requisitionPaymentDate = {
      title: messages('finance-4.key288')/*计划付款日期*/, dataIndex: 'requisitionPaymentDate', hide: true,
      render: value => moment(value).format('YYYY-MM-DD')
    };

    scheduleDate = {
      title: messages('finance-4.key288')/*计划付款日期*/, dataIndex: 'scheduleDate', hide: true,
      render: value => moment(value).format('YYYY-MM-DD')
    };

    remark = { title: messages('finance-4.key63')/*备注*/, dataIndex: 'remark', hide: true };

    editRemark = {
      title: messages('finance-4.key63')/*备注*/, dataIndex: 'remark', hide: true,
      render: (value, record) => (
        <EditInput
          value={value}
          onChange={editValue => this.wrappedInstance.editAccount("remark", editValue, record)}
        />
      )
    };

    pendingOption = [
      { key: '01', label: messages('finance-4.key103')/*非暂挂*/ },
      { key: '02', label: messages('finance-4.key104')/*暂挂*/ }
    ];

    pending = {
      title: messages('finance-4.key280')/*暂挂状态*/, dataIndex: 'pendings', hide: true, width: 150,
      render: (value, record) => (
        <EditSelect
          option={this.pendingOption}
          value={{
            key: record.pending,
            label: this.pendingOption.find(item => item.key === record.pending).label
          }}
          onChangeError={this.wrappedInstance.state.editCellError}
          onChange={value => this.wrappedInstance.editAccount("pending", value, record)}
          disabled={this.wrappedInstance.state.editing}
        />
      )
    };

    createdDate = {
      title: messages('finance-4.key71')/*创建日期*/, dataIndex: 'createdDate', hide: true,
      render: value => moment(value).format('YYYY-MM-DD')
    };

    formName = { title: messages('finance-4.key273')/*表单类型*/, dataIndex: 'formName', hide: true };

    ledgerStatus = {
      title: messages('finance-4.key275')/*核算状态*/, dataIndex: 'ledgerStatus', hide: true,
      render: value => this.ledgerMap.get(value) || '-'
    };

    ledgerMap = new Map([
      ['S', messages('finance-4.key276')/*生成成功*/],
      ['P', messages('finance-4.key289')/*处理中*/],
      ['F', messages('finance-4.key14')/*生成失败*/]
    ]);

    getColumns = key => {
      let columns = [];
      switch (key) {
        case 'Unpaid':
          columns = [this.companyName, this.departmentName, this.requisitionDate, this.documentNumber, this.employeeName,
            this.currency, this.unPaidAmount, this.unPaidPayableAmount, this.unPaidCurrentPayAmount,
            this.unPaidPaymentMethodCategoryName, this.paymentMethodCategoryType, this.partnerCategoryName, this.unPaidAccountNumber,
            this.paymentStatusName, this.cshTransactionClassName, this.requisitionPaymentDate, this.editRemark,
            this.pending, this.formName, this.requisitionTime];
          break;
        case 'Paying':
          let innnerColumns = [{
            title: messages('common.operation')/*操作*/, dataIndex: 'operated', fixed: 'right', width: 110, render: (value, record) => {
              const menu = (
                <Menu>
                  <Menu.Item>
                    <a onClick={() => this.wrappedInstance.handleOperate(record, 'success')}>{messages('finance-4.key120')/*确认成功*/}</a>
                  </Menu.Item>
                  <Menu.Item>
                    <a onClick={() => this.wrappedInstance.handleOperate(record, 'error')}>{messages('finance-4.key121')/*确认失败*/}</a>
                  </Menu.Item>
                </Menu>
              );
              return (
                <div>
                  <a onClick={() => this.checkPaymentDetail(record)}>{messages('common.view')/*查看*/}</a>
                  {
                    record.isReceiptUpload === 2 ? (
                      <span>
                         <span className="ant-divider"/>
                        <a onClick={() => this.handleReceipt(record)}>
                          {record.receiptUrl ? messages('finance-4.key417')/*回单查看*/ : messages('finance-4.key418')/*回单上传*/}
                        </a>
                      </span>
                    ) : undefined
                  }
                  {
                    record.paymentStatus !== 'W' && (
                      <span>
                      <span className="ant-divider"/>
                      <Dropdown overlay={menu} placement="bottomRight">
                        <a>{messages('common.more')/*更多*/}<Icon type="down" /></a>
                      </Dropdown>
                     </span>
                    )
                  }
                </div>
              )}
          }];
          columns = [this.documentCompanyName, this.departmentName, this.billCode, this.customerBatchNo,
            this.documentNumber, this.employeeName, this.currency, this.amount, this.paymentTypeName,
            this.partnerCategoryName, this.payeeAccountNumber, this.payDate, this.paymentStatusName,
            this.cshTransactionClassName, this.scheduleDate, this.remark, this.createdDate, ...innnerColumns];
          break;
        case 'Success':
          const operation = [{
            title: messages('common.operation')/*操作*/,
            dataIndex: 'operate',
            fixed: 'right',
            render: (value, record) => this.wrappedInstance.state.radioValue === 'ONLINE_PAYMENT'
              ? (
                <span>
                  <a onClick={() => this.wrappedInstance.handleRefund(record)}>{messages('finance-4.key165')/*退票*/}</a>
                  {this.wrappedInstance.ledgerStatus(record)}
                </span>
              )
              : record.ledgerStatus === 'F'
                ? (<a onClick={() => this.wrappedInstance.handleReLedger(record)}>{messages('finance-4.key114')/*重新生成凭证*/}</a>)
                : '-'
          }];
          columns = [this.documentCompanyName, this.departmentName, this.billCode, this.customerBatchNo,
            this.documentNumber, this.employeeName, this.currency, this.amount, this.paymentTypeName,
            this.partnerCategoryName, this.payeeAccountNumber, this.payDate, this.paymentStatusName,
            this.cshTransactionClassName, this.scheduleDate, this.remark, this.createdDate , this.ledgerStatus,
            ...operation];
          break;
        case 'Fail':
          columns = [this.documentCompanyName, this.departmentName, this.billCode, this.customerBatchNo,
            this.documentNumber, this.employeeName, this.currency, this.amount, this.paymentTypeName,
            this.partnerCategoryName, this.payeeAccountNumber, this.payDate, this.paymentStatusName,
            this.cshTransactionClassName, this.scheduleDate, this.remark, this.createdDate , this.ledgerStatus];
          break;
        case 'refund-check':
          columns = [this.billCode, this.customerBatchNo, this.documentNumber, this.employeeName, this.currency,
            this.amount, this.paymentTypeName, this.partnerCategoryName, this.payeeAccountNumber, this.payDate];
          break;
        default:
          break;
      }
      return columns;
    };

    checkPaymentDetail = record => {
      openSlideFrame.openPayCashDetail({
        id: record.id
      }, {}, this);
    };

    handleReceipt = record => {
      if (record.receiptUrl) {
        window.open(record.receiptUrl, '_blank')
      } else {
        ReceiptUpload.open(this, this.handleUpload, record)
      }
    };

    handleUpload = ({data, closeModal, context}, record) => {
      context.setState({ confirmLoading: true });
      paymentService.receiptUpload({
        ...data,
        setOfBookId: record.setOfBooksId,
        id: record.id,
        tenantId: record.tenantId
      }).then(() => {
        context.setState({ confirmLoading: false });
        closeModal();
        this.wrappedInstance.advancedTableRef.getList();
        message.success(messages('common.operate.success')/*操作成功*/)
      }).catch(e => {
        context.setState({ confirmLoading: false });
        message.error(e.response.data.message)
      })
    };

    handleClickDoc = record => {
      if (record.entityType === 1002) {
        if (record.documentCategory === 'VENDOR_PAYMENT') {
          openSlideFrame.openCorporateReportDetail({
            expenseReportOID: record.entityOid,
            entry: 'view'
          }, {
            noPadding: true,
            className: 'corporate-payment-report-detail'
          }, this);
        } else {
          openSlideFrame.openExpenseReport({
            expenseReportOID: record.entityOid,
            entry: 'view'
          }, {}, this);
        }
      } else if(record.entityType === 7001) {
        openSlideFrame.openPaymentDetail({
          paymentRequestOID: record.entityOid,
        }, {}, this);
      } else {
        this.wrappedInstance.setState({ loading: true });
        paymentService.getFormOID(record.entityOid).then(res => {
          this.wrappedInstance.setState({ loading: false }, () => {
            openSlideFrame.openLoanReport({
              formOID: res.data.formOID,
              loanBillOID: record.entityOid,
              pathname: 'pay-workbench'
            }, {}, this);
          });
        }).catch(e => {
          this.wrappedInstance.setState({ loading: false });
          message.error(e.response.data.message);
        })
      }
    };

    noticeAlert = (selectedData, isFail = false) => {
      if (selectedData.length === 0) {
        this.wrappedInstance.setState({
          errorAlert: null,
          buttonDisabled: true
        });
      } else {
        let currency = selectedData[0].currency, amount = 0, flag = false;
        selectedData.every(item => {
          if (item.currency !== currency) {
            flag = true;
            return false
          }
          isFail ? (amount += item.amount) : (amount += item.currentPayAmount);
          return true
        });
        if (flag) {
          this.wrappedInstance.setState({
            errorAlert: (
              <span>
                { messages('finance-4.key290')/*已选择*/ }
                <span className='default-color-font' style={{ fontWeight: 'bold' }}> {selectedData.length} </span>
                { messages('finance-4.key291')/*项*/ }
                <span className="ant-divider"/>
                { messages('finance-4.key292')/*不同币种、不同付款机构不可同时支付*/ }
              </span>
            ),
            buttonDisabled: true
          });
        } else {
          this.wrappedInstance.setState({
            buttonDisabled: false,
            errorAlert: undefined
          });
        }
      }
    };

    handleTableTitle = (tableTitle, selectedData, isFail) => {
      let flag = isFail ? 'amount' : 'currentPayAmount';
      let selectMap = selectedData.reduce((current, item) => {
        if (current[item.currency]) {
          current[item.currency].amount += item[flag];
          current[item.currency].total += 1;
        } else {
          current[item.currency] = {
            amount: item[flag],
            total: 1
          }
        }
        return current
      }, {});
      let result;
      if (selectedData.length) {
        let temp = Object.keys(selectMap);
        result = (
          <div>
            {messages('common.has.selected')/*已选*/}
            <span className="ant-divider"/>
            {temp.map((item, index) => (
              <span>
                {messages('finance-4.key293',{arg1: item})/*金额：{arg1}*/}
                <span className="num-style">{this.filterMoney(selectMap[item].amount, queryCurrencyPrecision(item), true)}</span>
                <span className="ant-divider"/>
                {messages('finance-4.key294')/*交易笔数：*/}
                <span className="num-style">{selectMap[item].total}{messages('finance-4.key295')/*笔*/}</span>
                {index !== temp.length - 1 && <span className="ant-divider"/>}
              </span>
            ))}
          </div>
        )
      } else {
        result = (
          <div>
            {messages('common.all')/*全部*/}
            <span className="ant-divider"/>
            {tableTitle.map((item, index) => {
              return (
                <span key={index}>
                {messages('finance-4.key293',{arg1: item.currency})/*金额：{arg1}*/}
                  <span className="num-style">{this.filterMoney(item.totalAmount, queryCurrencyPrecision(item.currency), true)}</span>
                <span className="ant-divider"/>
                  {messages('finance-4.key294')/*交易笔数：*/}
                  <span className="num-style">{item.documentNumber}{messages('finance-4.key295')/*笔*/}</span>
                  {index !== tableTitle.length - 1 && <span className="ant-divider"/>}
              </span>
              )
            })}
          </div>
        )
      }
      return (selectedData.length > 0 || tableTitle.length > 0) ? result : null
    };

    initConfig = (key, params, setOfBookId) => {
      if (setOfBookId) {
        return new Promise((resolve, reject) => {
          this.wrappedInstance.setState({ loading: true });
          paymentService.getOptions({ setOfBookId }).then(res => {
            let radioValue = optionsMap.get(res.data.defPaymentMethods[0]).itemCode;
            this.wrappedInstance.setState({
              loading: false,
              radioOption: orderTab(handleOptions(res.data.ablePaymentMethods)),
              radioValue,
              payAll: !res.data.isPartPay,
              setOfBookId
            }, () => {
              this.wrappedInstance.handleColumns && this.wrappedInstance.handleColumns();
              this.handleData(radioValue, params, key).then(response => {
                resolve(response)
              }).catch(e => {
                reject(e);
              })
            })
          }).catch(e => {
            this.wrappedInstance.setState({ loading: false });
            reject(e);
          })
        });
      } else {
        return this.handleData(params.paymentMethodCategory, params, key);
      }
    };

    handleData = (radioValue, params, key) => {
      params.paymentMethodCategory = radioValue;
      let tempParams = {
        ...params,
        paymentMethodCategory: radioValue
      };
      delete tempParams.page;
      delete tempParams.size;
      if (key !== 'Unpaid') {
        let isRefundOrFail = params.paymentMethodCategory === 'ONLINE_PAYMENT' && key === 'Fail';
        tempParams.isRefundOrFail = isRefundOrFail;
        !isRefundOrFail && (tempParams.paymentStatus = key[0])
      }
      return new Promise((resolve, reject) => {
        Promise.all([
          paymentService.getAmount(tempParams, key),
          paymentService.getList(params, key)
        ]).then(response => {
          this.wrappedInstance.setState({ tableTitle: response[0].data }, resolve(response[1]));
        }).catch(e => {
          reject(e)
        })
      });
    };

    handleTableChange = (pagination, filters, sorter) => {
      const map = {
        currentPayAmounts: 'currentPayAmount',
        requisitionDate: 'requisition_date',
        documentNumber: 'document_number'
      };
      this.wrappedInstance.setState({
        sortDTOs: sorter.order ? [{
          property: map[sorter.columnKey] || sorter.columnKey,
          direction: sorter.order === 'ascend' ? 'ASC' : 'DESC'
        }] : []
      }, this.wrappedInstance.advancedTableRef.getList);
    };

    onClearSelected = (callBack = () => {}) => {
      const { rowSelection } = this.wrappedInstance.state;
      rowSelection.selectedRowKeys = [];
      this.wrappedInstance.setState({ rowSelection, selectedData: [] }, callBack);
    };

    getSelection = (callBack = () => {}) => {
      const onSelectChange = selectedRowKeys => {
        let { rowSelection } = this.wrappedInstance.state;
        rowSelection.selectedRowKeys = selectedRowKeys;
        this.wrappedInstance.setState({ rowSelection });
      };
      const onSelectItem = (record, selected, selectedRows, nativeEvent, callBack, callbackParams) => {
        const { selectedData } = this.wrappedInstance.state;
        if (selected) {
          selectedData.push(record);
        } else {
          selectedData.deleteObj(record, 'id')
        }
        this.wrappedInstance.setState({ selectedData },() => { selectedRows && callBack(selectedData, callbackParams) });
      };

      const onSelectAll = (selected, selectedRows, changeRows, callBack, callbackParams) => {
        const { length } = changeRows;
        changeRows.map((changeRow, index) => onSelectItem(changeRow, selected, index === length - 1, null , callBack, callbackParams));
      };
      return function (callbackParams) {
        return ({
          selectedRowKeys: [],
          onChange: onSelectChange,
          onSelect: (record, selected, selectedRows, nativeEvent) => onSelectItem(record, selected, selectedRows, nativeEvent, callBack, callbackParams),
          onSelectAll: (selected, selectedRows, changeRows) => onSelectAll(selected, selectedRows, changeRows, callBack, callbackParams)
        })
      }
    };

    render() {
      let props = { ...this.props, ref: this.setWrappedInstance };
      return(
        <WrappedComponent
          getSearchForm={this.getSearchForm}
          getColumns={this.getColumns}
          noticeAlert={this.noticeAlert}
          handleTableTitle={this.handleTableTitle}
          initConfig={this.initConfig}
          handleTableChange={this.handleTableChange}
          onClearSelected={this.onClearSelected}
          getSelection={this.getSelection}
          {...props}
        />
      )
    }
  }

  function mapStateToProps(state) {
    return {
      company: state.login.company,
      loginUser: state.login.loginUser,
      tenant: state.login.tenant
    }
  }

  return connect(mapStateToProps)(hoc);
};

export default DataHoc;
